package com.example.permissionsapply;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.permissionsapply.permissions.PermissionResultAdapter;
import com.example.permissionsapply.permissions.PermissionUtil;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_call_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                applyCallPhonePermission();
            }
        });
    }

    /**
     * 申请拨打电话的权限
     */
    private void applyCallPhonePermission() {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //申请拨打电话的权限
            PermissionUtil.getInstance().request(this, new String[]{Manifest.permission.CALL_PHONE}, new PermissionResultAdapter() {
                @Override
                public void onPermissionGranted() {
                    callPhone("10086");
                    Log.d(TAG,"权限通过");
                }
            });
        } else {
            callPhone("10086");
        }
    }

    /**
     * 拨打电话
     */
    private void callPhone(String phone) {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "请打开拨打电话权限", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
        MainActivity.this.startActivity(intent);
    }

}
